import csv
import numpy as np
from collections import Counter
import os


def read_class_data(csv_name):
    """
    读取CSV文件中的数学成绩数据，跳过表头并处理数据格式问题
    :param csv_name: CSV文件名
    :return: 数学成绩列表
    """
    scores = []
    if not os.path.exists(csv_name):
        print(f"文件 {csv_name} 不存在，请检查路径是否正确。")
        return scores
    with open(csv_name, 'r', encoding='utf-8') as file:
        reader = csv.reader(file)
        next(reader)  # 跳过表头
        for row in reader:
            if len(row) > 1 and row[2].strip():  # 检查是否有足够列且第二列不为空
                try:
                    scores.append(float(row[2]))  # 尝试转换为浮点数
                except ValueError:
                    continue  # 如果转换失败，跳过这一行
    return scores


class1_data = read_class_data('class1.csv')
class2_data = read_class_data('class2.csv')
class3_data = read_class_data('class3.csv')

if not class1_data and not class2_data and not class3_data:
    print("没有读取到有效的数学成绩数据，请检查CSV文件内容。")
else:
    # 合并所有班级的数学成绩到一个NumPy数组
    all_scores = np.array(class1_data + class2_data + class3_data)

    # 计算均值
    mean_score = np.mean(all_scores) if all_scores.size > 0 else 0
    # 计算中位数
    median_score = np.median(all_scores) if all_scores.size > 0 else 0
    # 计算众数
    count = Counter(all_scores)
    mode_result = count.most_common(1)[0][0] if count else 0
    # 计算标准差
    std_score = np.std(all_scores) if all_scores.size > 0 else 0
    # 计算方差
    var_score = np.var(all_scores) if all_scores.size > 0 else 0

    # 打印所有统计数据
    print(f"数学成绩的均值: {mean_score}")
    print(f"数学成绩的中位数: {median_score}")
    print(f"数学成绩的众数: {mode_result}")
    print(f"数学成绩的标准差: {std_score}")
    print(f"数学成绩的方差: {var_score}")

